package com.cmwa.solution.base.controller;

import java.util.Enumeration;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 日志级别管理
 * @author luoxy
 * @date  2015年8月13日 下午2:36:34
 */
@Controller
@RequestMapping("/logManager")
@SuppressWarnings("unchecked")
public class LoggerManagerController extends BaseController {

	@RequestMapping("loading")
	public String loading() {
		return "sys/log-manager";
	}

	@RequestMapping("infoLogger")
	@ResponseBody
	public String infoLogger(@RequestParam("loggerName") String loggerName) {
		Enumeration<Logger> currentLoggers = LogManager.getCurrentLoggers();
		StringBuilder sb = new StringBuilder();
		while (currentLoggers.hasMoreElements()) {
			Logger logger = currentLoggers.nextElement();
			if (logger.getName().indexOf(loggerName) > -1) {
				sb.append(logger.getName()).append(":")
						.append(logger.getLevel()).append("|");
			}
		}
		return sb.toString();
	}

	@RequestMapping("changeLoggerLevel")
	@ResponseBody
	public String changeLoggerLevel(
			@RequestParam("loggerName") String loggerName,
			@RequestParam("level") String level) {
		if ("root".equalsIgnoreCase(loggerName)) {
			LogManager.getRootLogger().setLevel(Level.toLevel(level));
			return "SUCCESS!";
		}
		
		String result = "logger not exist.";
		Enumeration<Logger> currentLoggers = LogManager.getCurrentLoggers();
		while (currentLoggers.hasMoreElements()) {
			Logger logger = currentLoggers.nextElement();
			if (logger.getName().indexOf(loggerName) > -1) {
				logger.setLevel(Level.toLevel(level));
				result = "SUCCESS!";
			}
		}	
		return result;
	}
}
